package cn.otrue.patienthealthmanager.view;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.WeekTableListAdpater;
import cn.otrue.patienthealthmanager.bean.SugarTemplateMonitorDetail;
import cn.otrue.patienthealthmanager.bean.SugarTemplateMonitorPlanTime;
import cn.otrue.patienthealthmanager.utils.MyConst;

public class WeekTable extends RelativeLayout implements OnClickListener {

	private Context context;
	private View rootView;
	private NoScrollListView lv_week_table;
	private List<SugarTemplateMonitorDetail> planData = new ArrayList<SugarTemplateMonitorDetail>();
	private SugarTemplateMonitorPlanTime timeData;

	private WeekTableListAdpater adapter;
	private int[] time = { R.id.tv_week_table_time1, R.id.tv_week_table_time2,
			R.id.tv_week_table_time3, R.id.tv_week_table_time4,
			R.id.tv_week_table_time5, R.id.tv_week_table_time6,
			R.id.tv_week_table_time7, R.id.tv_week_table_time8 };
	private LinearLayout ll_week_title1;
	private LinearLayout ll_week_title2;
	private LinearLayout ll_week_time;

	public WeekTable(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initView();

	}

	public void changeView() {
		ll_week_title1.setLayoutParams(new LinearLayout.LayoutParams(
				MyConst.width, MyConst.width / 9));
		ll_week_title2.setLayoutParams(new LinearLayout.LayoutParams(
				MyConst.width, (MyConst.width - 8) / 9));
		ll_week_time.setLayoutParams(new LinearLayout.LayoutParams(
				MyConst.width, (MyConst.width - 8) / 9));

	}

	private void initView() {
		LayoutInflater inflater = LayoutInflater.from(context);
		rootView = inflater.inflate(R.layout.item_week_table, this);
		ll_week_title1 = (LinearLayout) rootView
				.findViewById(R.id.ll_week_title1);
		ll_week_title2 = (LinearLayout) rootView
				.findViewById(R.id.ll_week_title2);
		ll_week_time = (LinearLayout) rootView.findViewById(R.id.ll_week_time);
		lv_week_table = (NoScrollListView) rootView
				.findViewById(R.id.lv_week_table);

		adapter = new WeekTableListAdpater(context, planData);
		lv_week_table.setAdapter(adapter);

		// 初始化时间
		for (int i = 0; i < time.length; i++) {
			TextView tv_time = (TextView) rootView.findViewById(time[i]);
			tv_time.setTag(i);

			tv_time.setOnClickListener(this);
		}

	}

	public void setType(int type) {
		if (type == MyConst.SHOW_PLAN) {
			adapter.setType(MyConst.SHOW_PLAN);
			for (int i = 0; i < time.length; i++) {
				TextView tv_time = (TextView) rootView.findViewById(time[i]);
				tv_time.setTag(i);

				tv_time.setOnClickListener(new MyNullClickListener());
			}

		}
	}

	public class MyNullClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

		}

	}

	/**
	 * 改变WeekTable的值
	 * 
	 * @param detailData
	 *            计划列表
	 * @param timeDatap
	 *            时间
	 */
	public void changeData(List<SugarTemplateMonitorDetail> detailData,
			SugarTemplateMonitorPlanTime timeData) {

		this.planData.clear();
		this.planData.addAll(detailData);
		adapter.notifyDataSetChanged();
		this.timeData = timeData;
		((TextView) rootView.findViewById(time[0])).setText(timeData
				.getBefore_dawn());
		((TextView) rootView.findViewById(time[1])).setText(timeData
				.getEmpty_stomach());
		((TextView) rootView.findViewById(time[2])).setText(timeData
				.getAfter_breakfast());
		((TextView) rootView.findViewById(time[3])).setText(timeData
				.getBefore_lunch());
		((TextView) rootView.findViewById(time[4])).setText(timeData
				.getAfter_lunch());
		((TextView) rootView.findViewById(time[5])).setText(timeData
				.getBefore_dinner());
		((TextView) rootView.findViewById(time[6])).setText(timeData
				.getAfter_dinner());
		((TextView) rootView.findViewById(time[7])).setText(timeData
				.getBefore_sleep());

	}

	public List<SugarTemplateMonitorDetail> getDetailData() {
		return planData;
	}

	public SugarTemplateMonitorPlanTime getTimeData() {
		return timeData;
	}

	@Override
	public void onClick(View v) {
		SetTimeDialog std = new SetTimeDialog((TextView) v);
		std.show(((Activity) context).getFragmentManager(), "timePicker");
	}

	class SetTimeDialog extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener {

		TextView tv;

		public SetTimeDialog(TextView tv) {
			super();
			this.tv = tv;
		}

		@SuppressLint("NewApi")
		public Dialog onCreateDialog(Bundle savedInstanceState) {

			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			String dateStr = tv.getText().toString();
			String[] dateArr = dateStr.split(":");

			if (dateArr.length == 2) {
				hour = Integer.parseInt(dateArr[0]);
				minute = Integer.parseInt(dateArr[1]);
			}
			TimePickerDialog tpd = new TimePickerDialog(getActivity(), this,
					hour, minute, DateFormat.is24HourFormat(getActivity()));
			return tpd;
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			if (isReasonableTime(tv, hourOfDay, minute)) {
				String timeStr = timeFormat(hourOfDay) + ":"
						+ timeFormat(minute);
				tv.setText(timeStr);
				Object tag = tv.getTag();
				if (tag != null) {

					switch (Integer.parseInt(tag.toString())) {
					case 0:
						timeData.setBefore_dawn(timeStr);
						break;
					case 1:
						timeData.setEmpty_stomach(timeStr);
						break;
					case 2:
						timeData.setAfter_breakfast(timeStr);
						break;
					case 3:
						timeData.setBefore_lunch(timeStr);
						break;
					case 4:
						timeData.setAfter_lunch(timeStr);
						break;
					case 5:
						timeData.setBefore_dinner(timeStr);
						break;
					case 6:
						timeData.setAfter_dinner(timeStr);
						break;
					case 7:
						timeData.setBefore_sleep(timeStr);
						break;

					}

				}
			} else {
				Toast.makeText(context, "时间不在正确范围内", 0).show();
			}

		}

		private boolean isReasonableTime(TextView tv2, int hourOfDay, int minute) {
			int position = getPositionForArr(tv2.getId(), time);

			if (position == 0) {
				return compareTime(hourOfDay, minute, time[1]);
			} else if (position == (time.length - 1)) {
				return compareTime(hourOfDay, minute, time[time.length - 2]);
			} else {
				return compareTime(hourOfDay, minute, time[position + 1])
						&& !compareTime(hourOfDay, minute, time[position - 1]);
			}

		}

		private boolean compareTime(int hour, int minute, int compareId) {

			String compareTime = ((TextView) rootView.findViewById(compareId))
					.getText().toString();
			String[] dateArr = compareTime.split(":");

			if (dateArr.length == 2) {

				int compareHour = Integer.parseInt(dateArr[0]);
				int compareMinute = Integer.parseInt(dateArr[1]);
				if ((compareHour * 60 + compareMinute) <= (hour * 60 + minute)) {
					return false;
				} else {
					return true;
				}
			}
			return false;
		}

		private int getPositionForArr(int i, int[] time) {
			for (int j = 0; j < time.length; j++) {
				if (i == time[j]) {
					return j;
				}
			}
			return 0;
		}

		private String timeFormat(int time) {
			if (time < 10) {
				return "0" + time;
			}
			return time + "";
		}
	}
}
